import os, datetime
from rest_framework import permissions, filters, response, status
from rest_framework.decorators import action
from apps.api.project.models import ProjectModel
from apps.api.project.serializers import \
    ProjectModelSerializer, \
    GetTestCaseNameModelSerializer, \
    GetConfigNameModelSerializer, \
    RunProjectModelSerializer
from apps.basic.environment.models import EnvironmentModel
from apps.api.interface.models import InterfaceModel
from apps.api.testcase.models import TestCaseModel
from base.settings import YML_FILE_PATH
from utils import viewsets, common
from utils.response import data_response, message_response


class ProjectViewSet(viewsets.MyViewSets):
    queryset = ProjectModel.objects.all()
    serializer_class = ProjectModelSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['create_time']

    @action(methods=["GET"], detail=False)
    def cases(self, request, *args, **kwargs):
        """获取项目测试用例列表名称"""
        serializer = self.get_serializer(instance=self.get_queryset().filter(is_delete=0), many=True)
        result = data_response(data=serializer.data)
        return response.Response(result)

    @action(methods=["GET"], detail=False)
    def configs(self, request, *args, **kwargs):
        """获取项目公共配置列表名称"""
        serializer = self.get_serializer(instance=self.get_queryset().filter(is_delete=0), many=True)
        result = data_response(data=serializer.data)
        return response.Response(result)

    @action(methods=["POST"], detail=True)
    def run(self, request, *args, **kwargs):
        # 获取要运行的项目对象
        project_obj = self.get_object()
        super().create(request, *args, **kwargs)
        # 获取要运行的环境对象
        env = EnvironmentModel.objects.filter(id=request.data["env_id"]).filter(is_delete=0).first()
        # 创建时间戳文件夹
        stamp_path = os.path.join(YML_FILE_PATH, datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d%H%M%S"))
        os.makedirs(stamp_path)
        interfaces_obj = InterfaceModel.objects.filter(project_id=project_obj.id).filter(is_delete=0)
        if len(interfaces_obj) == 0:
            message = {"run": "此项目下没有接口，无法运行！"}
            result = message_response(code=1, message=message)
            return response.Response(result, status=status.HTTP_200_OK)
        run_cases_obj = []
        for interface_obj in interfaces_obj:
            cases_obj = TestCaseModel.objects.filter(interface_id=interface_obj.id).filter(is_delete=0)
            if cases_obj.exists():
                run_cases_obj.extend(list(cases_obj))
        if len(run_cases_obj) == 0:
            message = {"run": "此项目下没有用例，无法运行！"}
            result = message_response(code=1, message=message)
            return response.Response(result, status=status.HTTP_200_OK)
        for run_case_obj in run_cases_obj:
            # 组装用例
            common.assemble_case(stamp_path, env, run_case_obj)
        # 运行用例
        return common.run_case(project_obj.name, stamp_path)

    def get_serializer_class(self):
        if self.action == "cases":
            return GetTestCaseNameModelSerializer
        elif self.action == "configs":
            return GetConfigNameModelSerializer
        elif self.action == "run":
            return RunProjectModelSerializer
        return self.serializer_class

    def perform_create(self, serializer):
        if self.action == "run":
            pass
        else:
            serializer.save()


